package com.mazaiting.auth.security.core.userdetails.user;

import cn.hutool.core.collection.CollectionUtil;
import com.mazaiting.auth.enums.PasswordEncoderTypeEnum;
import com.mazaiting.auth.security.core.userdetails.base.BaseUserDetails;
import com.mazaiting.manager.dto.UserAuthDTO;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Collection;


/**
 * 系统管理用户认证信息
 */
@Setter
@Getter
public class SysUserDetails extends BaseUserDetails {

    /**
     * 扩展字段：用户ID
     */
    private Long userId;

    /**
     * 扩展字段：部门ID
     */
    private Long deptId;

    /**
     * 密码
     */
    private String password;
    /**
     * 是否可用
     */
    private Boolean enabled;
    /**
     * 角色
     */
    private Collection<GrantedAuthority> authorities;
    /**
     * 账户是否过期(1:过期，0:没过期)
     */
    private Boolean accountNonExpired;

    /**
     * 密码是否过期(1:过期，0:没过期)
     */
    private Boolean credentialsNonExpired;

    /**
     * 账户是否锁定(1:锁定，0:没锁定)
     */
    private Boolean accountNonLocked;

    /**
     * 系统管理用户
     */
    public SysUserDetails(UserAuthDTO userAuthDto) {
        this.userId = userAuthDto.getUserId();
        this.username = userAuthDto.getUsername();
        this.password = PasswordEncoderTypeEnum.BCRYPT.getPrefix() + userAuthDto.getPassword();
        this.enabled = userAuthDto.getEnabled();
        this.accountNonExpired = userAuthDto.getAccountNonExpired();
        this.accountNonLocked = userAuthDto.getAccountNonLocked();
        this.credentialsNonExpired = userAuthDto.getCredentialsNonExpired();
        this.deptId = userAuthDto.getDeptId();
        // 赋值角色代码
        if (CollectionUtil.isNotEmpty(userAuthDto.getRoles())) {
            authorities = new ArrayList<>();
            userAuthDto.getRoles().forEach(roleCode -> authorities.add(new SimpleGrantedAuthority(roleCode)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
